* ======================================
* ---------- Split Immigrants ----------
* ======================================


	use $dta\EstimationSample.dta, clear


* Split by origin
* ===============

	destring Voter_birthcountry,replace
	rename Voter_birthcountry bc
	
	gen region = ""
	replace region = "Scandinavia"	if bc == 0 | bc ==101 | bc == 106
	replace region = "EuRus" if bc >= 100 & bc < 200 & region != "Scandinavia"
	replace region = "Africa"		if bc >= 200 & bc < 400
	replace region = "Asia" 		if bc >= 400 & bc < 600
	replace region = "NAmerica" 	if bc >= 600 & bc < 700
	replace region = "SAmerica" 	if bc >= 700 & bc < 800
	
	* Generate estimation variables
	foreach var in EuRus Africa Asia NAmerica SAmerica{
		gen Imm1`var'Any = 1*(Imm1Any == 1 & region == "`var'")
		gen Imm1`var'Same = 1*(Imm1Same == 1 & region == "`var'")	
		gen Imm2`var'Any = 1*(Imm2Any == 1 & region == "`var'")
		gen Imm2`var'Same = 1*(Imm2Same == 1 & region == "`var'")	
	}

	

* Estimate models
* ===============

	egen idbsu = group(Voter_id Voter_bsu)
	gen period = 1*(year == 2019)
	xtset idbsu period
	estimates clear


	foreach var in EuRus Africa Asia NAmerica SAmerica{
		foreach net in Imm1 Imm2{
			preserve
			keep if `net' == 1			// Network sample
			keep if region == "`var'" 	// Region sample
			
			sum Voter_turnout 	// mean depvar
			local meandepvar = string(r(mean)*100, "%15.2fc")
		
			gen Any = `net'`var'Any
			gen Same = `net'`var'Same
			eststo m_`net'`var': xtreg Voter_turnout Any Same i.period, ///
				i(idbsu) fe cluster(Voter_bsu)
			quietly estadd local meandep `meandepvar', replace	
			restore
		}
	}


* Export table
* ============

	esttab m_* ///
		using $tbls\SplitImmigrants.tex, replace  style(tex) ///
		prehead("\begin{tabular}{l*{11}{c}} \hline\hline \\ ") ///
		posthead("\hline \\") ///
		fragment ///
		mtitles("3-digit" "2-digit" "3-digit" "2-digit" "3-digit" ///
			"2-digit" "3-digit" "2-digit" "3-digit" "2-digit") ///
		mgroups("\shortstack{Europe \\ inc. Russia}" "Africa" "Asia" ///
			"\shortstack{North \\ America}" "\shortstack{South \\ America}", ///
			pattern(1 0 1 0 1 0 1 0 1 0) span prefix(\multicolumn{@span}{c}{) ///
			suffix(}) end(\cmidrule(lr){2-3} \cmidrule(lr){4-5} ///
			\cmidrule(lr){6-7} \cmidrule(lr){8-9} \cmidrule(lr){10-11})) ///
		label se b(%9.3f) se(%9.3f) nostar ///
		refcat(Any "\shortstack{ No network candidate }") ///
		coeflabels(Any "Any District" Same "Same District" ) ///
		drop(_cons *.period ) noomitted nobaselevels ///
		nonotes stats(N N_clust meandep, labels( ///
			"Observations" "Clusters" "Mean turnout (\%)" ) ///
			fmt(%15.0fc %15.0fc %15.0fc)) substitute(\_ _) ///
		prefoot("\hline") ///
		postfoot("\hline\hline \\ \end{tabular}")
